<template>
  <d2-container>
    <template slot="header">现货现货套期-新增</template>
    <div style="margin-bottom:10px;font-size:14px">
      <span style="color:red">* </span>为必填项
    </div>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">基础信息</p>
      </template>
      <el-form
        class="filter-container"
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="部门名称" prop="department_name">
              <el-select
                v-model="ruleForm.department_name"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option
                  v-for="item in selectDepartsList"
                  :key="item.department_name"
                  :label="item.name"
                  :value="item.department_name"
                >
                  <span style="float: left">{{ item.name }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略名称" prop="strategy_name">
              <el-input
                placeholder="请输入"
                v-model="ruleForm.strategy_name"
                clearable
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="套期比例">
              <el-col :span="10">
                <el-input-number
                  size="mini"
                  :precision="2"
                  :step="0.01"
                  :min="0"
                  v-model="ruleForm.hedging_ratio_lower"
                ></el-input-number>
              </el-col>
              <el-col :span="2">
                <div style="text-align:center">~</div>
              </el-col>
              <el-col :span="10">
                <el-input-number
                  size="mini"
                  :precision="2"
                  :step="0.01"
                  :max="1.5"
                  v-model="ruleForm.hedging_ratio_upper"
                ></el-input-number>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略类型">
              <el-input value="现货-现货套期" clearable readonly> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略目的">
              <el-select
                v-model="ruleForm.strategy_objective"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option label="期货套利" value="1"></el-option>
                <el-option label="期现套利" value="2"></el-option>
                <el-option label="套期保值" value="3"></el-option>
                <el-option label="其他" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最大占用资金">
              <el-input
                placeholder="请输入"
                v-model="max_occupation_funds"
                clearable
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="损失限额">
              <el-input
                placeholder="请输入"
                v-model="loss_limit"
                clearable
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预期盈利">
              <el-input
                placeholder="请输入"
                v-model="profit_expectation"
                clearable
                type="number"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="风险利润比">
              <el-input
                placeholder="请输入"
                v-model="risk_profit_ratio"
                clearable
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预期投资回报率">
              <el-input
                placeholder="请输入"
                v-model="expected_return_on_investment"
                clearable
                readonly
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略开始日期" prop="strategy_start_date">
              <el-date-picker
                v-model="ruleForm.strategy_start_date"
                type="date"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
                style="width:100%;"
                :picker-options="startDatePicker"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略结束日期" prop="strategy_end_date">
              <el-date-picker
                v-model="ruleForm.strategy_end_date"
                type="date"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd"
                style="width:100%;"
                :picker-options="endDatePicker"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="套期方式" prop="hedging_method">
              <el-select
                v-model="ruleForm.hedging_method"
                placeholder="请选择"
                style="width:100%;"
              >
                <el-option label="滚动套" value="1"></el-option>
                <el-option label="逐笔套" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="策略层级" prop="strategy_hierarchy">
              <el-select
                v-model="ruleForm.strategy_hierarchy"
                placeholder="请选择"
                style="width:100%;"
                :disabled="true"
              >
                <el-option label="策略" value="1"></el-option>
                <el-option label="策略-指令" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item label="策略描述">
              <el-input
                class="resizeNone"
                style="width:169%"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                placeholder="请输入"
                v-model="ruleForm.strategy_description"
              >
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card shadow="never" class="d2-mb titleline">
      <template slot="header" style="height:66px;">
        <span class="title_x el-button--primary fl"></span>
        <p class="title_l fl">套期组合</p>
      </template>
      <el-form
        class="filter-container"
        label-width="110px"
        style="margin-bottom:15px"
      >
        <el-row :gutter="20">
          <el-col>
            <el-form-item label="策略盈亏">
              <el-input
                class="resizeNone"
                style="width:50%"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
                readonly
                v-model="strategy_count"
              >
              </el-input>
              <el-button
                type="primary"
                size="mini"
                style="margin-left: 20px;"
                @click="count"
              >
                计算
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-card shadow="never" class="d2-mb">
        <div style="margin-bottom: 15px;">现货</div>
        <el-button type="default" size="mini" @click.prevent="addSpotDataRow()">
          <d2-icon name="plus" />
          增行
        </el-button>
        <el-button
          type="default"
          size="mini"
          icon="el-icon-delete"
          @click.prevent="delSpotData()"
        >
          删行
        </el-button>
        <div style="margin-top:15px">
          <el-form :model="tradeData" ref="spotFrom">
            <el-table
              :data="tradeData.spotData"
              border
              fit
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
              @selection-change="soptRow"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号"> </el-table-column>
              <el-table-column label="品名*">
                <template slot-scope="scope">
                  <div style="display: flex;">
                    <el-form-item
                      :prop="'spotData.' + scope.$index + '.name_cn'"
                      :rules="rules.name_cn"
                    >
                      <el-input
                        placeholder="请选择内容"
                        v-model="scope.row.name_cn"
                        readonly
                      ></el-input>
                    </el-form-item>
                    <el-button
                      type="primary"
                      plain
                      style="height: 30px;margin:5px 0 0 10px;line-height:7px"
                      @click="getMore(scope.row)"
                      size="mini"
                      >选择</el-button
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="方向*" prop="direction">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'spotData.' + scope.$index + '.direction'"
                    :rules="rules.direction"
                  >
                    <el-select
                      v-model="scope.row.direction"
                      placeholder="请选择"
                      style="width:100%;"
                      :disabled="true"
                    >
                      <el-option label="采购" value="1"></el-option>
                      <el-option label="销售" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="参考价格*" prop="reference_price">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'spotData.' + scope.$index + '.reference_price'"
                    :rules="rules.reference_price"
                  >
                    <el-input
                      type="number"
                      placeholder="请输入"
                      @keyup.native="proving2($event)"
                      v-model="scope.row.reference_price"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="最大数量*" prop="max_amount">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'spotData.' + scope.$index + '.max_amount'"
                    :rules="rules.max_amount"
                  >
                    <el-input
                      type="number"
                      @keyup.native="proving2($event)"
                      v-model="scope.row.max_amount"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单位*">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'spotData.' + scope.$index + '.commodity_unit'"
                    :rules="rules.commodity_unit"
                  >
                    <el-input
                      v-model="scope.row.commodity_unit"
                      :disabled="true"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="币种" prop="currency">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'spotData.' + scope.$index + '.currency'"
                    :rules="rules.currency"
                  >
                    <el-select
                      v-model="scope.row.currency"
                      placeholder="请选择"
                      style="width:100%;"
                      @change="quotExchangeRate2($event, scope.$index)"
                    >
                      <el-option
                        v-for="item in selectCurrencyList"
                        :key="item.symbol"
                        :label="item.currency"
                        :value="item.symbol"
                      >
                        <span style="float: left">{{ item.currency }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.remarks"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-card>
      <el-dialog :visible.sync="getA" v-if="getA" title="品名">
        <trade-name
          :closeValue="'TypeBiome'"
          @closeMoule="closeMoule"
        ></trade-name>
      </el-dialog>
      <el-card shadow="never" class="d2-mb">
        <div style="margin-bottom: 15px;">现货</div>
        <el-button
          type="default"
          size="mini"
          @click.prevent="addFuturesDataRow()"
        >
          <d2-icon name="plus" />
          增行
        </el-button>
        <el-button
          type="default"
          size="mini"
          icon="el-icon-delete"
          @click.prevent="delFuturesData()"
        >
          删行
        </el-button>
        <div style="margin-top:15px">
          <el-form :model="tradeData" ref="futuresFrom">
            <el-table
              :data="tradeData.futuresData"
              border
              fit
              :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
              @selection-change="futuresRow"
            >
              <el-table-column type="selection" width="40"> </el-table-column>
              <el-table-column type="index" label="序号"> </el-table-column>
              <el-table-column label="品名*">
                <template slot-scope="scope">
                  <div style="display: flex;">
                    <el-form-item
                      :prop="'futuresData.' + scope.$index + '.name_cn'"
                      :rules="rules.name_cn"
                    >
                      <el-input
                        placeholder="请选择内容"
                        v-model="scope.row.name_cn"
                        readonly
                      ></el-input>
                    </el-form-item>
                    <el-button
                      type="primary"
                      plain
                      style="height: 30px;margin:5px 0 0 10px;line-height:7px"
                      @click="getMore(scope.row)"
                      size="mini"
                      >选择</el-button
                    >
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="方向*" prop="direction">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'futuresData.' + scope.$index + '.direction'"
                    :rules="rules.direction"
                  >
                    <el-select
                      v-model="scope.row.direction"
                      placeholder="请选择"
                      style="width:100%;"
                      :disabled="true"
                    >
                      <el-option label="采购" value="1"></el-option>
                      <el-option label="销售" value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="参考价格*" prop="reference_price">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'futuresData.' + scope.$index + '.reference_price'"
                    :rules="rules.reference_price"
                  >
                    <el-input
                      type="number"
                      placeholder="请输入"
                      @keyup.native="proving2($event)"
                      v-model="scope.row.reference_price"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="最大数量*" prop="max_amount">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'futuresData.' + scope.$index + '.max_amount'"
                    :rules="rules.max_amount"
                  >
                    <el-input
                      type="number"
                      @keyup.native="proving2($event)"
                      v-model="scope.row.max_amount"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="单位*">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'futuresData.' + scope.$index + '.commodity_unit'"
                    :rules="rules.commodity_unit"
                  >
                    <el-input
                      v-model="scope.row.commodity_unit"
                      :disabled="true"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="币种" prop="currency">
                <template slot-scope="scope">
                  <el-form-item
                    :prop="'futuresData.' + scope.$index + '.currency'"
                    :rules="rules.currency"
                  >
                    <el-select
                      v-model="scope.row.currency"
                      placeholder="请选择"
                      style="width:100%;"
                      @change="quotExchangeRate1($event, scope.$index)"
                    >
                      <el-option
                        v-for="item in selectCurrencyList"
                        :key="item.symbol"
                        :label="item.currency"
                        :value="item.symbol"
                      >
                        <span style="float: left">{{ item.currency }}</span>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="备注">
                <template slot-scope="scope">
                  <el-input
                    placeholder="请输入"
                    v-model="scope.row.remarks"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-card>
    </el-card>
    <el-button
      type="primary"
      size="mini"
      style="float:right;margin-left: 10px;"
      @click="submitForm('ruleForm', 'spotFrom', 'futuresFrom')"
    >
      保存
    </el-button>
  </d2-container>
</template>

<script>
import tradeName from "../model/tradeName.vue";
import { addStrategy } from "@/api/url_info.js";
import { currency } from "@/api/url_info.js";
import { getDepartments } from "@/api/url.js";
import { quotExchangeRate } from "@/api/url_info.js";
import { strategyCal } from "@/api/url_info.js";
export default {
  //现货现货套期-新增
  name: "spotFuturesHedging",
  components: {
    "trade-name": tradeName
  },
  data() {
    return {
      startDatePicker: this.beginDate(),
      endDatePicker: this.processDate(),
      strategy_count: null,
      bstrategy_count: "",
      loss_limit: "",
      profit_expectation: "",
      max_occupation_funds: "",
      expected_return_on_investment: "",
      selectCurrencyList: [],
      selectDepartsList: [],
      risk_profit_ratio: "",
      ruleForm: {
        //基础信息
        department_name: "",
        strategy_name: "",
        hedging_ratio_lower: "0",
        hedging_ratio_upper: "0",
        strategy_type: "2",
        strategy_objective: "",
        strategy_start_date: "",
        strategy_end_date: "",
        hedging_method: "1",
        strategy_hierarchy: "1",
        strategy_description: ""
      },
      tradeData: {
        //交易信息 现货
        spotData: [
          {
            trade_type: "1",
            direction: "1",
            name: "",
            name_cn: "",
            reference_price: "",
            max_amount: "",
            commodity_unit: "",
            market: "",
            currency: "",
            remarks: "",
            spare_value: ""
          }
        ],
        //现货
        futuresData: [
          {
            trade_type: "1",
            direction: "2",
            name: "",
            name_cn: "",
            reference_price: "",
            max_amount: "",
            commodity_unit: "",
            market: "",
            currency: "",
            remarks: "",
            spare_value: ""
          }
        ]
      },
      soptlistRow: [],
      futureslistRow: [],
      futuresNum: 1,
      spotNum: 1,
      rules: {
        department_name: [
          { required: true, message: "请选择部门名称", trigger: "change" }
        ],
        currency: [
          { required: true, message: "请选择币种", trigger: "change" }
        ],
        strategy_name: [
          { required: true, message: "请输入策略名称", trigger: "blur" }
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        strategy_start_date: [
          {
            required: true,
            message: "请选择策略开始日期",
            trigger: "change"
          }
        ],
        strategy_end_date: [
          {
            required: true,
            message: "请选择策略结束日期",
            trigger: "change"
          }
        ],
        hedging_method: [
          { required: true, message: "请选择套期方式", trigger: "change" }
        ],
        strategy_hierarchy: [
          { required: true, message: "请选择策略层级", trigger: "change" }
        ],
        direction: [
          { required: true, message: "请选择方向", trigger: "change" }
        ],
        commodity_unit: [
          { required: true, message: "请选择单位", trigger: "blur" }
        ],
        reference_price: [
          { required: true, message: "请输入参考价格", trigger: "blur" }
        ],
        max_amount: [
          { required: true, message: "请输入最大数量", trigger: "blur" }
        ],
        instrument: [
          { required: true, message: "请选择合约", trigger: "change" }
        ],
        offset_flag: [
          { required: true, message: "请选择开/平", trigger: "change" }
        ],
        max_volume: [
          { required: true, message: "请输入最大手数", trigger: "blur" }
        ],
        name_cn: [{ required: true, message: "请选择品名", trigger: "blur" }]
      },
      getA: false,
      row: null
    };
  },
  watch: {
    profit_expectation: function(val) {
      this.risk_profit_ratio = (
        parseInt(val) / parseFloat(this.loss_limit)
      ).toFixed(4);
      this.expected_return_on_investment = (
        parseInt(val) / parseFloat(this.max_occupation_funds)
      ).toFixed(4);
      if (isNaN(this.risk_profit_ratio)) {
        this.risk_profit_ratio = "";
      }
      if (isNaN(this.expected_return_on_investment)) {
        this.expected_return_on_investment = "";
      }
      if (this.risk_profit_ratio == "Infinity") {
        this.risk_profit_ratio = "--";
      }
      if (this.expected_return_on_investment == "Infinity") {
        this.expected_return_on_investment = "--";
      }
    },
    loss_limit: function(val) {
      this.risk_profit_ratio = (
        parseInt(this.profit_expectation) / parseFloat(val)
      ).toFixed(4);
      if (isNaN(this.risk_profit_ratio)) {
        this.risk_profit_ratio = "";
      }
      if (this.risk_profit_ratio == "Infinity") {
        this.risk_profit_ratio = "--";
      }
      if (this.expected_return_on_investment == "Infinity") {
        this.expected_return_on_investment = "--";
      }
    },
    max_occupation_funds: function(val) {
      this.expected_return_on_investment = (
        parseInt(this.profit_expectation) / parseFloat(val)
      ).toFixed(4);
      if (isNaN(this.expected_return_on_investment)) {
        this.expected_return_on_investment = "";
      }
      if (this.risk_profit_ratio == "Infinity") {
        this.risk_profit_ratio = "--";
      }
      if (this.expected_return_on_investment == "Infinity") {
        this.expected_return_on_investment = "--";
      }
    }
  },
  created() {
    this.handle_currencyChange();
    this.handle_getDepartments();
  },
  methods: {
    //计算
    counts() {
      //策略盈亏=同一品名现货销售参考价格*最大数量
      //-同一品名现货采购参考价格*最大数量
      let spot = this.tradeData.spotData,
        futures = this.tradeData.futuresData,
        purchase = [], //采购
        sale = []; //销售
      if (spot.length > 0) {
        spot.forEach(item => {
          if (item.direction == "1") {
            purchase.push(item);
          }
        });
      }
      if (futures.length > 0) {
        futures.forEach(item => {
          if (item.direction == "2") {
            sale.push(item);
          }
        });
      }
      let saleSum = 0,
        purchaseSum = 0;
      sale.forEach(item => {
        if (
          (item.currency == "CNY" || item.currency == "") &&
          item.commodity_unit.indexOf("吨") != -1
        ) {
          saleSum += item.reference_price * item.max_amount;
        } else if (
          item.currency != "CNY" &&
          item.currency != "" &&
          item.commodity_unit.indexOf("吨") == -1
        ) {
          if (item.commodity_unit.indexOf("千克") != -1) {
            saleSum +=
              item.reference_price * item.max_amount * 1000 * item.spare_value;
          } else if (item.commodity_unit.indexOf("克") != -1) {
            saleSum +=
              item.reference_price *
              item.max_amount *
              1000000 *
              item.spare_value;
          } else {
            saleSum +=
              item.reference_price * item.max_amount * item.spare_value;
          }
        } else if (
          (item.currency == "CNY" || item.currency == "") &&
          item.commodity_unit.indexOf("吨") == -1
        ) {
          if (item.commodity_unit.indexOf("千克") != -1) {
            saleSum += item.reference_price * item.max_amount * 1000;
          } else if (item.commodity_unit.indexOf("克") != -1) {
            saleSum += item.reference_price * item.max_amount * 1000000;
          } else {
            saleSum += item.reference_price * item.max_amount;
          }
        } else if (
          item.currency != "CNY" &&
          item.commodity_unit.indexOf("吨") != -1
        ) {
          saleSum += item.reference_price * item.max_amount * item.spare_value;
        }
      });

      purchase.forEach(item => {
        if (
          (item.currency == "CNY" || item.currency == "") &&
          item.commodity_unit.indexOf("吨") != -1
        ) {
          purchaseSum += item.reference_price * item.max_amount;
        } else if (
          item.currency != "CNY" &&
          item.currency != "" &&
          item.commodity_unit.indexOf("吨") == -1
        ) {
          if (item.commodity_unit.indexOf("千克") != -1) {
            purchaseSum +=
              item.reference_price * item.max_amount * 1000 * item.spare_value;
          } else if (item.commodity_unit.indexOf("克") != -1) {
            purchaseSum +=
              item.reference_price *
              item.max_amount *
              1000000 *
              item.spare_value;
          } else {
            purchaseSum +=
              item.reference_price * item.max_amount * item.spare_value;
          }
        } else if (
          (item.currency == "CNY" || item.currency == "") &&
          item.commodity_unit.indexOf("吨") == -1
        ) {
          if (item.commodity_unit.indexOf("千克") != -1) {
            purchaseSum += item.reference_price * item.max_amount * 1000;
          } else if (item.commodity_unit.indexOf("克") != -1) {
            purchaseSum += item.reference_price * item.max_amount * 1000000;
          } else {
            purchaseSum += item.reference_price * item.max_amount;
          }
        } else if (
          item.currency != "CNY" &&
          item.commodity_unit.indexOf("吨") != -1
        ) {
          purchaseSum +=
            item.reference_price * item.max_amount * item.spare_value;
        }
      });
      console.log("1232143", saleSum, purchaseSum);
      this.strategy_count = saleSum - purchaseSum;
    },
    count() {
      let info = this.tradeData.spotData.concat(this.tradeData.futuresData);
      info.forEach(item => {
        item.created_time = this.dateNow();
      });
      strategyCal({ data: info })
        .then(res => {
          this.strategy_count = res.result;
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //禁止输入负数
    proving2(e) {
      var keynum = window.event ? e.keyCode : e.which; //获取键盘码
      var keychar = String.fromCharCode(keynum); //获取键盘码对应的字符
      if (keynum == 189 || keynum == 109) {
        this.$message.warning("禁止输入负数");
        e.target.value = "";
      }
    },
    //树形结构转换为扁平数组
    treeToList(tree) {
      var queen = [];
      var out = [];
      queen = queen.concat(tree);
      while (queen.length) {
        var first = queen.shift();
        if (first.sub_depart) {
          queen = queen.concat(first.sub_depart);
          delete first["sub_depart"];
        }
        out.push(first);
      }
      return out;
    },
    // 查询部门
    handle_getDepartments() {
      getDepartments()
        .then(res => {
          this.selectDepartsList = [];
          var data1 = res.result;
          var arr = this.treeToList(data1);
          for (var i = 0; i < arr.length; i++) {
            this.selectDepartsList[i] = {
              name: arr[i]["name"],
              department_name: arr[i]["id"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 查询汇率
    quotExchangeRate1(e, index) {
      quotExchangeRate({ currency: e })
        .then(res => {
          let data = res.result,
            arr = [];
          for (var i = 0; i < data.length; i++) {
            arr.push(data[i]);
          }
          let end = arr.pop(),
            rate = null;
          if (e == "USD") {
            rate = end.USD;
          } else if (e == "EUR") {
            rate = end.EUR;
          } else if (e == "JPY") {
            rate = end.JPY;
          } else if (e == "HKD") {
            rate = end.HKD;
          } else if (e == "CNY") {
            rate = 100;
          }
          this.tradeData.futuresData[index].spare_value = (rate / 100).toFixed(
            2
          );
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    quotExchangeRate2(e, index) {
      quotExchangeRate({ currency: e })
        .then(res => {
          let data = res.result,
            arr = [];
          for (var i = 0; i < data.length; i++) {
            arr.push(data[i]);
          }
          let end = arr.pop(),
            rate = null;
          if (e == "USD") {
            rate = end.USD;
          } else if (e == "EUR") {
            rate = end.EUR;
          } else if (e == "JPY") {
            rate = end.JPY;
          } else if (e == "HKD") {
            rate = end.HKD;
          } else if (e == "CNY") {
            rate = 100;
          }
          this.tradeData.spotData[index].spare_value = (rate / 100).toFixed(2);
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    // 查询币种
    handle_currencyChange() {
      currency()
        .then(res => {
          this.selectCurrencyList = [];
          var data1 = res.result.results;
          for (var i = 0; i < data1.length; i++) {
            this.selectCurrencyList[i] = {
              currency: data1[i]["name"],
              symbol: data1[i]["symbol"]
            };
          }
        })
        .catch(err => {
          this.$message.error(err.msg);
        });
    },
    //保存
    async submitForm(formName, spotName, futuresName) {
      let hedging_portfolio = this.tradeData.spotData.concat(
        this.tradeData.futuresData
      );
      hedging_portfolio.forEach(item => {
        if (item.spare_value == "") {
          item.spare_value = 1;
        }
      });
      let params = {
        operation: "ADD",
        //基础信息
        strategy_info: {
          status: this.ruleForm.status,
          department_name: this.ruleForm.department_name,
          strategy_name: this.ruleForm.strategy_name,
          hedging_ratio_lower: this.ruleForm.hedging_ratio_lower,
          hedging_ratio_upper: this.ruleForm.hedging_ratio_upper,
          strategy_type: this.ruleForm.strategy_type,
          strategy_objective: this.ruleForm.strategy_objective || 1,
          max_occupation_funds: this.max_occupation_funds || "0",
          loss_limit: this.loss_limit || "0",
          profit_expectation: this.profit_expectation || "0",
          risk_profit_ratio: this.risk_profit_ratio || "0",
          expected_return_on_investment:
            this.expected_return_on_investment || "0",
          strategy_formulate_date: this.ruleForm.strategy_formulate_date,
          strategy_start_date: this.ruleForm.strategy_start_date,
          strategy_end_date: this.ruleForm.strategy_end_date,
          strategy_hierarchy: this.ruleForm.strategy_hierarchy,
          hedging_method: this.ruleForm.hedging_method,
          strategy_description: this.ruleForm.strategy_description
        },
        //交易信息
        trade_info: hedging_portfolio
      };
      const rule1 = new Promise((resolve, reject) => {
        this.$refs[formName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      const rule2 = new Promise((resolve, reject) => {
        this.$refs[spotName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      const rule3 = new Promise((resolve, reject) => {
        this.$refs[futuresName].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
      Promise.all([rule1, rule2, rule3]).then(() => {
        addStrategy(params)
          .then(res => {
            this.$message({
              message: res.result,
              type: "success"
            });
            this.closeing.closePage(
              this.$store.getters["d2admin/page/allPage"],
              this.$store.getters["d2admin/page/currentPage"]
            );
            this.$router.push({
              path: "/hedging_strategy/tactical_management?type=first"
            });
          })
          .catch(err => {
            this.$message.error(err.msg);
          });
      });
    },
    //这里是控制结束日期不能小于开始日期
    beginDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.ruleForm.strategy_end_date) {
            //如果结束时间不为空，则小于结束时间
            return (
              new Date(self.ruleForm.strategy_end_date).getTime() <
              time.getTime()
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDate() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.ruleForm.strategy_start_date) {
            //如果开始时间不为空，则结束时间大于开始时间
            return (
              new Date(self.ruleForm.strategy_start_date).getTime() >
              time.getTime() + 8.64e7
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    //获取表格选中时的数据
    soptRow(val) {
      this.soptlistRow = val;
    },
    futuresRow(val) {
      this.futureslistRow = val;
    },
    //删除选中行
    delSpotData() {
      let val = this.soptlistRow;
      if (val.length > 0) {
        for (let i = 0; i < this.soptlistRow.length; i++) {
          val.forEach((val, index) => {
            this.tradeData.spotData.forEach((v, i) => {
              if (val.spotNum === v.spotNum) {
                this.tradeData.spotData.splice(i, 1);
              }
            });
          });
        }
        // 删除完数据之后清除勾选框
        this.$refs.table.clearSelection();
      } else {
        this.$message({
          type: "warning",
          message: "请选择删除数据"
        });
      }
    },
    delFuturesData() {
      let val = this.futureslistRow;
      if (val.length > 0) {
        for (let i = 0; i < this.futureslistRow.length; i++) {
          val.forEach((val, index) => {
            this.tradeData.futuresData.forEach((v, i) => {
              if (val.futuresNum === v.futuresNum) {
                this.tradeData.futuresData.splice(i, 1);
              }
            });
          });
        }
        this.$refs.table.clearSelection();
      } else {
        this.$message({
          type: "warning",
          message: "请选择删除数据"
        });
      }
    },
    //品名弹框
    getMore(row) {
      this.getA = true;
      this.row = row;
    },
    //品名弹窗
    closeMoule(e) {
      if (e.id) {
        this.row.name_cn = e.commodity;
        this.row.name = e.id;
        this.row.commodity_unit = e.commodity_unit;
        this.getA = false;
      } else {
        this.$message({
          message: "请选择一条数据",
          type: "warning"
        });
      }
    },
    // 增加行
    addSpotDataRow() {
      var list = {
        spotNum: this.spotNum,
        trade_type: "1",
        direction: "1",
        name: "",
        name_cn: "",
        reference_price: "",
        max_amount: "",
        commodity_unit: "",
        market: "",
        currency: "",
        remarks: "",
        spare_value: ""
      };
      this.tradeData.spotData.push(list);
      this.spotNum += 1;
    },
    addFuturesDataRow() {
      var list = {
        futuresNum: this.futuresNum,
        trade_type: "1",
        direction: "2",
        name: "",
        name_cn: "",
        reference_price: "",
        max_amount: "",
        commodity_unit: "",
        market: "",
        currency: "",
        remarks: "",
        spare_value: ""
      };
      this.tradeData.futuresData.push(list);
      this.futuresNum += 1;
    }
  }
};
</script>
<style lang="scss" scoped>
.resizeNone {
  .el-textarea__inner {
    resize: none;
  }
}
.el-form-item {
  margin-bottom: 0px !important;
}
</style>
